﻿var fbLoginStatus = false;
var accessToken;
var fbId = null;

//function getFbLoginStatus() {
//    FB.getLoginStatus(function (response) {
//        if (response.authResponse) {
//            fbLoginStatus = true;
//        } else {
//            // no user session available, someone you dont know
//        }
//        alert(fbLoginStatus);
//    });
//}

//function showFavorites() {
//    ///hides all pages except favorites
//    $("#tabs-1").css("display", "none");
//    $("#tabs-3").css("display", "none");
//    $("#songContent").css("display", "none");


// }

function initFacebook() {
    ///code for init fb api
    if (!$("#fb-root").length) {
        return;
    }

    window.fbAsyncInit = function () {
        ///response when javascript api is ready
        FB.init({
            appId: '140390589306756', // App ID
            //                channelURL: '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            oauth: true, // enable OAuth 2.0
            xfbml: true  // parse XFBML
        });

        FB.Event.subscribe('auth.login', function (response) {
            login();
        });
        FB.Event.subscribe('auth.logout', function (response) {
            logout();
        });
        FB.getLoginStatus(function (response) {
            ///query login
            thisGetLoginStatus();
        });

        setFbProfile();



    };

    // Load the SDK Asynchronously
    (function (d) {
        var js, id = 'facebook-jssdk'; if (d.getElementById(id)) { return; }
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/fr_FR/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
    } (document));
}

/*---------------------------FB------------------------------*/

function setFbProfile() {
    //takes saved id and look for name and picture
    //has nothing to do with logged users
    if ($("#fbId").length) {
        var fbIds = $("#fbId").html().split('|');

        if (fbIds.length >= 0) {
            ///case more than 1 person
            for (var i = 0; i < fbIds.length; i++) {
                ///cycle through each Ids
                FB.api('/' + fbIds[i] + "/?fields=name,picture", function (response) {
                    $("#fbPictures").prepend("<img src=" + response.picture + " />");
                    $("#fbNames").prepend(response.name + "&nbsp;");

                    //                    $.logThis("from fb call back"+language);
                });
            }

            ///more than one, plural fbText
            if (fbIds.length > 1) {
                if (language == "fr-FR") {
                    $("#fbText").html("ont contribué à cette chanson");
                }
                else {
                    ///nothing to change in english
                    //                    $("#fbText").html("ont contribué à cette chanson");
                }
            }

        }
        //        else if (fbIds.length == 1) {
        //            ///case only 1 person
        //            FB.api('/' + fbIds[0] + "/?fields=name,picture", function (response) {
        //                fbId = response.id;
        //                $("#fbPicture").attr("src", response.picture);
        //                $("#fbName").html("&nbsp;&nbsp;" + response.name + $("#fbName").html());
        //            });
        //        }
    }
}


function login() {
    ///event called when user is logged in
    FB.api('/me', function (response) {
        fbId = response.id;
        $.logThis("called back after login (login button clicked and user logged in through new window)");
        this.fillFBInfo(fbId);
    });
}

function logout() {
    //            alert('You have successfully logged out!');
    ///todo:get back to "login" fbbutton
}
function thisGetLoginStatus() {

    FB.api('/me', function (response) {

        ///cosole show either undefined(=notlogged) or an ind(=logged)
        fbId = response.id;
        this.fillFBInfo(fbId);
        if (FB.getAuthResponse() != null) {
            accessToken = FB.getAuthResponse()['accessToken'];
            $.logThis('Access Token = ' + accessToken);
        }

    });
}

function fillFBInfo(fbId) {
    ///either at satrup or from call back after login

    $.logThis("current logged facebook id user:" + fbId);
    if (fbId != null) {
        ///fill div used for identifying fb user in creating/editing song
        $("#SubmittedBy").attr("value", fbId);
        ///if logged, show picture and name
        FB.api('/' + fbId + "/?fields=name,picture", function (response) {
            fbId = response.id;
            $("#loggedFbPicture").attr("src", response.picture);
            $("#loggedFbPicture").show();
            $("#loggedFbName").html("&nbsp;&nbsp;" + response.name + $("#loggedFbName").html());
        });
        ///user logged, hide login button
        $("#fbLogingButton").hide();
        $("#fbTextWithLoginButton").hide();

    }
    else {
        ///user not logged, show connection button
        $("#fbLogingButton").show();
        $("#fbTextWithLoginButton").show();
    }
}

function loginButton() {
    ///provide method for logging in, replaces fbml login button <fb:login-button>
    FB.login(function (response) {
        if (response.authResponse) {
            $.logThis('Welcome!  Fetching your information.... ');
            FB.api('/me', function (response) {
                $.logThis('Good to see you, ' + response.name + '.');
            });
        } else {
            $.logThis('User cancelled login or did not fully authorize.');
        }
    }, {
        scope: 'email,user_birthday,status_update,publish_stream,publish_actions'
    }
    );

}